package czk.concrent.threadpool.shutdownnow;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author chenzhangkun
 * @ClassName ShouDownNowTest
 * @description: TODO
 * @date 2024年08月20日
 */
public class ShouDownNowAndCancelTest {
	public static void main(String[] args) throws InterruptedException {
		List<Callable<Void>> tasks=new ArrayList<>();

		// 收集执行线程
		for (int i = 0; i < 10; i++) {
			int finalI=i;
			tasks.add(()->{
				System.out.println("任务"+finalI+"开始执行");
				Thread.sleep(500);
				return null;
			});
		}
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		new Thread(()->{
			try {
				executorService.invokeAll(tasks);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("invokeAll returned");
		}).start();

		Thread.sleep(500);
		System.out.println("shutdown");
		// 立即关闭线程池，此时不会关闭，需要对返回值进行处理
		List<Runnable> runnables = executorService.shutdownNow();
		for (Runnable runnable : runnables) {
			if (runnable instanceof Future){
				// 强转
				Future future=(Future) runnable;
				future.cancel(false);
			}
		}
		System.out.println("finish shutdown");
	}
}
